package com.atguigu.yygh.cmn.service.impl;

import com.alibaba.excel.EasyExcel;
import com.atguigu.yygh.cmn.listener.DictListener;
import com.atguigu.yygh.cmn.mapper.DictMapper;
import com.atguigu.yygh.cmn.service.DictService;
import com.atguigu.yygh.common.exception.YyghException;
import com.atguigu.yygh.model.cmn.Dict;
import com.atguigu.yygh.vo.cmn.DictEeVo;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;

/**
 * <p>
 * 组织架构表 服务实现类
 * </p>
 *
 * @author atguigu
 * @since 2022-03-09
 */
@Service
public class DictServiceImpl extends ServiceImpl<DictMapper, Dict> implements DictService {

    @Autowired
    private DictListener dictListener;


    //根据数据id查询子数据列表
    @Cacheable(value = "dict")
    @Override
    public List<Dict> findChlidData(Long id) {
        QueryWrapper<Dict> wrapper = new QueryWrapper<>();
        wrapper.eq("parent_id", id);

        List<Dict> list = baseMapper.selectList(wrapper);

        for (Dict dict : list) {
            // 提取当前的id
            Long dictId = dict.getId();

            boolean flag = findChildFlag(dictId);

            dict.setHasChildren(flag);
        }
        return list;
    }

    //数据字典导出数据
    @Override
    public void exportData(HttpServletResponse response) {
        try {
            // 首先设置下载参数的设置
            // 1.参数类型
            response.setContentType("application/vnd.ms-excel");
            // 设置编码格式
            response.setContentType("utf-8");
            // 2.响应头信息的设置
            String fileName = URLEncoder.encode("数字字典", "UTF-8");
            response.setHeader("Content-disposition", "attachment;filename=" + fileName + ".xlsx");

            // 然后进行数据查询
            List<Dict> dictList = baseMapper.selectList(null);
            List<DictEeVo> dictEeVoList = new ArrayList<>();
            // 1.因为我们导出的bean是vo类，所以需要调用BeanUtils(spring包装的类中)
            for (Dict dict : dictList) {
                DictEeVo dictEeVo = new DictEeVo();
                BeanUtils.copyProperties(dict, dictEeVo);

                dictEeVoList.add(dictEeVo);
            }
            // 然后调用EasyExcel技术进行调用
            EasyExcel.write(response.getOutputStream(), DictEeVo.class)
                    .sheet("数据字典")
                    .doWrite(dictEeVoList);
        } catch (Exception e) {
            // 抛出自定义异常
            throw new YyghException(20001, "数据字典导出数据失败!");
        }
    }

    //数据字典导入数据
    // 因为当前没有返回值，所以无法使用@Cacheput 所以我们只能把缓存全部删除，然后重新加入。
    @CacheEvict(value = "dict", allEntries = true)
    @Override
    public void importData(MultipartFile file) {
        try {
            EasyExcel.read(file.getInputStream(), DictEeVo.class, dictListener).sheet().doRead();
        } catch (IOException e) {
            throw new YyghException(20001, "导入数据错误");
        }
    }

    // 判断当前是否含有子类
    public boolean findChildFlag(Long dictId) {
        QueryWrapper<Dict> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("parent_id", dictId);
        // 调用方法进行查询是否有子类
        Integer integer = baseMapper.selectCount(queryWrapper);

        return integer > 0;
    }


    //根据vlue值来取出数字字典中的name值
    @Override
    public String getName(String value) {
        QueryWrapper<Dict> wrapper = new QueryWrapper<>();
        wrapper.eq("value", value);
        Dict dict = baseMapper.selectOne(wrapper);
        return dict.getName();
    }

    //获取数据字典名称
    @Override
    public String getName(String parentDictCode, String value) {
        // 先根据DictCode值查询出来parent_id值
        QueryWrapper<Dict> wrapper = new QueryWrapper<>();
        wrapper.eq("dict_code", parentDictCode);
        Dict dict = baseMapper.selectOne(wrapper);

        // 然后根据parents_id和value值查询出来name的值
        QueryWrapper<Dict> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("parent_id", dict.getId()).eq("value", value);
        Dict dictDB = baseMapper.selectOne(queryWrapper);
        return dictDB.getName();
    }

    @Override
    public List<Dict> findByDictCode(String dictCode) {
        QueryWrapper<Dict> wrapper = new QueryWrapper<>();
        wrapper.eq("dict_code", dictCode);
        Dict dict = baseMapper.selectOne(wrapper);


        QueryWrapper<Dict> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("parent_id",dict.getId());
        List<Dict> list = baseMapper.selectList(queryWrapper);
        return list;
    }
}
